package server

import (
	"github.com/akirakazu/go-simplejson"
)

// "subscribe" command handler
func (s *Server) onSubscribe(id string, m *Pack) {
	if !m.Msg.Has("pattern") {
		msg := json.New()
		msg.Set("err", "pattern missing")
		s.response(id, m, msg)
		return
	}

	pattern := m.Msg.Get("pattern")

	// Create new listener
	l := newListener(m.Id, id, pattern)
	mgrbyte, _ := s.conns[id].identity.MarshalJSON()
	mgrid := string(mgrbyte)
	if _, ok := s.listeners[mgrid]; !ok {
		s.listeners[mgrid] = map[string]*listener{}
	}
	patternByte, _ := pattern.MarshalJSON()
	patternString := string(patternByte)
	s.listeners[mgrid][patternString] = l

	// Default response
	msg := json.New()
	msg.Set("msg", "ok")
	s.response(id, m, msg)
}

// "unsubscribe" command handler
func (s *Server) onUnsubscribe(id string, m *Pack) {
	if !m.Msg.Has("pattern") {
		msg := json.New()
		msg.Set("err", "pattern missing")
		s.response(id, m, msg)
		return
	}

	pattern := m.Msg.Get("pattern")

	// Search and remove matched listener
	wsbyte, _ := s.conns[id].identity.MarshalJSON()
	wsid := string(wsbyte)
	if _, ok := s.listeners[wsid]; ok {
		patternByte, _ := pattern.MarshalJSON()
		patternId := string(patternByte)
		delete(s.listeners[wsid], patternId)
	}
	msg := json.New()
	msg.Set("msg", "ok")
	s.response(id, m, msg)
}
